<?php

namespace addons\tools\controller\api\v1;

use addons\tools\model\MealLog;
use addons\tools\model\UserVip;
use app\common\model\User;
use think\Controller;
use think\Db;
use think\Exception;
use think\Log;
use Yansongda\Pay\Pay;

class Payment extends Controller
{

    /**
     * 回调
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \Yansongda\Pay\Exception\ContainerException
     * @throws \Yansongda\Pay\Exception\InvalidParamsException
     */
    public function notify()
    {
        Pay::config(config('pay'));
        $data = Pay::wechat()->callback();
        if (!$data) Log::error('验签失败！');
//        Log::error(json_encode($data));
        try {
            Db::transaction(function () use ($data) {
                $out_trade_no = $data['resource']['ciphertext']['out_trade_no'];
                $transaction_id = $data['resource']['ciphertext']['transaction_id'];
                $w = ['order_sn' => $out_trade_no, 'pay_status' => 0];
                if ($order = \addons\tools\model\MealOrder::where($w)->find()) {
                    //1.更新订单
                    $order->isUpdate(true)->save([
                        'pay_status' => 1,
                        'trade_no'   => $transaction_id,
                        'pay_time'   => time(),
                        'pay_price'  => bcdiv($data['resource']['ciphertext']['amount']['payer_total'], 100, 2)
                    ]);
                    $user = (new User())->where('status', 'normal')->find($order->user_id);
                    if ($user) {
                        //2.更新日期
                        $userVip = new  UserVip();
                        $userVip->where('user_id', $order->user_id)->update([
                            'update_vip' => 1,
                            'attach'     => json_encode(['meal_id' => $order->meal_id])
                        ]);
                        $userQueue = new \app\common\service\queue\User();
                        $userQueue->update_user_handle();
//                        $this->updateMemberTime((int)$order->user_id, $order->days, $number);
                        //3.添加记录
//                        $logData = [
//                            'user_id' => $order->user_id,
//                            'before'  => $user->tools_use_num,
//                            'after'   => $user->tools_use_num + $number,
//                            'memo'    => '购买会员新增次数'
//                        ];
//                        $this->createNumberLog($logData);
                    }

                }
            });
        } catch (\Exception $exception) {
            Log::error($exception->getMessage());
        }

        echo "SUCCESS";
//        return Pay::wechat()->success();
    }

    /**
     * 更新会员时间
     * @param int $user_id
     * @param int $number
     * @return void
     */
    private function updateMemberTime(int $user_id, int $days, int $number)
    {

        $userModel = new \app\common\model\User();
        $user = $userModel->where('id', $user_id)->find();
        $time = time();
        if (!$user->validity_time || $user->validity_time < $time)
            $time = $time + $days * 86400;
        else
            $time = $user->validity_time + $days * 86400;
        $number = $user->tools_use_num + $number;
        $user->validity_time = $time;
        $user->tools_use_num = $number;
        $user->save();
    }

    private function createNumberLog($data)
    {
        MealLog::createLog($data);
    }

}